package org.groupg.practice;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class PostJsonExample {
    // 定义 JSON 媒体类型
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        // 准备 JSON 请求体
        String json = "{\"username\":\"foo\", \"password\":\"bar\"}";
        RequestBody body = RequestBody.create(json, JSON);

        Request request = new Request.Builder()
            .url("https://api.example.com/login")
            .post(body) // 设置为 POST 请求并传入请求体
            .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println("POST success: " + response.body().string());
            } else {
                System.out.println("POST failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}